package baidu

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/url"
	"strings"
)

func HttpGets(url string) (string, error) {
	client := http.Client{}
	request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
	if err != nil {
		return "", err
	}
	request.Header.Set("headerParam", "header")
	resp, err := client.Do(request)
	if err != nil {
		return "", err
	}
	bytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	return string(bytes), nil
}

func HttpPost(urls string, param map[string]string) (string, error) {
	values := url.Values{}
	for k, v := range param {
		values.Add(k, v)
	}
	body2 := strings.NewReader(values.Encode())
	headers := map[string]string{}
	headers["Content-Type"] = "application/x-www-form-urlencoded"
	request, err := http.NewRequest("POST", urls, body2)
	for k, v := range headers {
		request.Header.Add(k, v)
	}
	res, err := http.DefaultClient.Do(request)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	bs, err := io.ReadAll(res.Body)
	if err != nil {
		return "", err
	}
	return string(bs), nil
}

func HttpFile(url,fileName string, files io.Reader) (string, error) {
	// 创建buffer
	var buffer bytes.Buffer
	//通过包multipart实现了MIME的multipart解析
	writer := multipart.NewWriter(&buffer)
	part, err := writer.CreateFormFile("file", fileName)
	if err != nil {
		return "", err
	}
	// 拷贝文件内容到新建FormFile中
	_, err = io.Copy(part, files)
	if err != nil {
		return "", err
	}
	err = writer.Close()
	if err != nil {
		return "", err
	}
	// 创建HTTP POST请求
	req, err := http.NewRequest("POST", url, &buffer)
	if err != nil {
		fmt.Println(err)
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	// 实例化一个http客户端对象
	client := &http.Client{}
	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	bs, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	fmt.Println(string(bs))
	fmt.Println(url)
	return string(bs), nil
}


func splitBytes(content []byte, size int) [][]byte {
	res := make([][]byte, 0)
	for len(content) > 0 {
		if len(content) > size {
			res = append(res, content[:size])
			content = content[size:]
		} else {
			res = append(res, content)
			content = nil
		}
	}
	return res
}